<template>
  <ion-page>
    <ion-content class="ion-padding">
      <div class="login-container">
        <h1><ion-icon style="font-size: 100px" :icon="personCircleOutline"/></h1>
        <form @submit.prevent="handleSubmit">
          <ion-item>
            <ion-icon :icon="person" slot="start"/>
            <ion-input 
              label="loginName"
              label-placement="floating"
              fill="solid"
              v-model="loginName"
              required
            ></ion-input>
          </ion-item>

          <ion-item>
            <ion-icon :icon="lockClosed" slot="start"/>
            <ion-input
              label="password"
              label-placement="floating"
              fill="solid"
              type="password"
              v-model="password"
              required
            ></ion-input>
          </ion-item>

          <ion-button 
            type="submit" 
            expand="block" 
            class="ion-margin-top"
          >
            LOGIN
          </ion-button>
        </form>
      </div>
    </ion-content>
  </ion-page>
</template>

<script setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { alertController, loadingController } from '@ionic/vue';
import { lockClosed, person, personCircleOutline } from 'ionicons/icons';
import { 
  IonPage,
  IonInput,
  IonButton,
  IonContent,
  IonItem,
  IonIcon
} from '@ionic/vue';
import axios from 'axios';

const router = useRouter();
const loginName = ref('');
const password = ref('');

const validateForm = () => {
  if (!loginName.value.trim()) {
    showError('loginName error');
    return false;
  }
  if (!password.value.trim()) {
    showError('Password error');
    return false;
  }
  return true;
};

const showError = async (message) => {
  const alert = await alertController.create({
    header: 'error',
    message,
    buttons: ['confirm']
  });
  await alert.present();
};

async function handleSubmit() {
  if (!validateForm()) return;
  
  const loading = await loadingController.create({ message: 'Login...' });
  await loading.present();

  try {
    const params = new URLSearchParams();
    params.append('loginName', loginName.value.trim());
    params.append('password', password.value.trim());
    const response = await axios.post(
      'https://www.svom-gwacn.cn/svomUPMS/oauth/token',
      params,
      { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }
    );
    
    localStorage.setItem('accessToken', response.data.data.accessToken);
    localStorage.setItem('isLoggedIn', 'true');
    localStorage.setItem('lastActiveTime', Date.now().toString());
    
    // 检查是否有重定向路径
    const redirectPath = localStorage.getItem('redirectPath');
    if (redirectPath) {
      localStorage.removeItem('redirectPath');
      await router.push(redirectPath);
    } else {
      await router.push('/tabs/eventlist');
    }
  } catch (error) {
    let errorMessage = 'Login failed';
    if (error.response?.data?.message) {
      errorMessage = error.response.data.message;
    }
    await showError(errorMessage);
  } finally {
    await loading.dismiss();
  }
}
</script>

<style scoped>
.login-container {
  max-width: 400px;
  margin: 2rem auto;
  text-align: center;
}
ion-item {
  margin-bottom: 1rem;
}

ion-button {
  --background: #3880ff;
  --background-activated: #3171e0;
}
@media (max-width: 576px) {
  .login-container {
    padding: 0 1rem;
    margin: 1rem auto;
  }
  
  h1 {
    font-size: 1.5rem;
    margin-bottom: 1.5rem;
    color: #3880ff;
  }
}

ion-loading.custom-loading {
  --spinner-color: #3880ff;
  --background: rgba(255, 255, 255, 0.9);
}
</style>